package de.tuberlin.julia.SFD_Numbers;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import com.google.code.microlog4android.Logger;
import com.google.code.microlog4android.LoggerFactory;

import de.tlabs.ahmad.trigger_server.TriggerServer;

import experiment.ApplyDesign;
import android.media.MediaPlayer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RemoteViews.RemoteView;
import android.widget.TextView;

public class AudioBtnPressedListener implements OnClickListener {
	private static final Logger logger = LoggerFactory.getLogger();

	private ApplyDesign applyDesign = null;
	
	Thread feedbackThread;
	MediaPlayer mp;
	PrintWriter output;
	
    TimeZone tz = TimeZone.getTimeZone("Europe/Berlin");
    Locale locale = Locale.GERMANY;
    final Calendar c = Calendar.getInstance(tz,locale);   
    SimpleDateFormat f= new SimpleDateFormat("HH:mm:ss.SS");
	
	public AudioBtnPressedListener(ApplyDesign applyDesign, MediaPlayer mp) {
		this.applyDesign = applyDesign;
		this.mp = mp;
	}

	@Override
	public void onClick(View v) {
		if (v instanceof TextView) {			
			TextView bt = (TextView) v;
			Object tag = bt.getTag();
			String digit = bt.getText().toString();
			
			if (!"C".equals(tag) && !"enter".equals(tag)) {
				logger.info("clicked");
				
				//TriggerServer.getOutputStream().print(43);
				
				feedbackThread = new Thread(new HapticFeedbackProvider(bt, applyDesign.getFeedbackDelay()));				
				feedbackThread.start();
				
				applyDesign.enterDigit(digit);			
				applyDesign.compareDigits(feedbackThread);
			}
		}
	}

	private class HapticFeedbackProvider implements Runnable {
		private final int haptDelay;

		public HapticFeedbackProvider(TextView bt, int haptDelay) {
			this.haptDelay = haptDelay;
		}

		@Override
		public void run() {
			try {
				if(haptDelay != 0)
					Thread.sleep(haptDelay);

				if (mp != null) {						
					mp.start();
				}
				TriggerServer.getOutputStream().print(21);
				TriggerServer.getOutputStream().flush();
				
            
	            f.setTimeZone(c.getTimeZone());
	            Date date = c.getTime();
	            logger.info("audio feedback " +  f.format(date));

			} catch (InterruptedException e) {
				logger.error(e.toString());
			} catch (IllegalStateException e) {
				logger.error(e.toString());
				e.printStackTrace();
			}
		}
	}
	

}

